﻿using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.SharpDevelop.Project;
using theeg.DependencyAnalysis.CommonAddin.Models;
using IProject = theeg.DependencyAnalysis.CommonAddin.Models.IProject;
using ISdProject = ICSharpCode.SharpDevelop.Project.IProject;

namespace theeg.DependencyAnalysis.SdAddin
{
    public class SdSolution : ISolution
    {
        private Solution _sdSolution;

        public Action BuildFinished { get; set; }

        public string FileName
        {
            get
            {
                return _sdSolution.FileName;
            }
        }

        public IList<IProject> Projects { get; private set; }

        public SdSolution(Solution solution)
        {
            _sdSolution = solution;
        }

        public void Refresh()
        {
            _sdSolution = ProjectService.OpenSolution;
            var solutionProjects = _sdSolution.Projects.ToList();
            var projects = (from project in solutionProjects
                            where SdProject.IsClrProject(project)
                            orderby project.Name
                            select new SdProject(project) { Name = project.Name, IsSelected = true }).Cast<IProject>().ToList();
            Projects = projects;
        }

        public void Build()
        {
            BuildEngine.BuildInGui(_sdSolution, new BuildOptions(BuildTarget.Build, Callback));
        }

        private void Callback(BuildResults results)
        {
            var handler = BuildFinished;
            if (handler != null)
            {
                handler();
            }
        }
    }
}
